<template>
  <aside class="sidebar card" @mouseleave="clearActiveCategory">
    <div class="sidebar-header">
      <h3 class="sidebar-title">商品分类</h3>
      <p class="sidebar-subtitle">选择您需要的商品类型</p>
    </div>
    <ul class="category-list">
      <li
        class="category-item all-products"
        :class="{ 'active': !activeCategoryId && !activeSubCategoryId }"
        @click="selectAllProducts"
      >
        <svg class="category-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M3 3h18v18H3z"/>
          <path d="M3 9h18"/>
          <path d="M9 21V9"/>
        </svg>
        <span>全部商品</span>
      </li>
      <li
        v-for="category in firstLevelCategories"
        :key="category.categoryId"
        class="category-item"
        :class="{ 'active': activeCategoryId === category.categoryId && !activeSubCategoryId }"
        @click="selectCategory(category)"
      >
        <svg class="category-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>
        </svg>
        <span>{{ category.categoryName }}</span>
        <!-- 二级分类 -->
        <ul v-if="activeCategoryId === category.categoryId && category.children && category.children.length" class="subcategory-list">
          <li
            v-for="sub in category.children"
            :key="sub.categoryId"
            class="subcategory-item"
            :class="{ 'active': activeSubCategoryId === sub.categoryId }"
            @click.stop="selectSubCategory(sub, category)"
          >
            {{ sub.categoryName }}
          </li>
        </ul>
      </li>
    </ul>
  </aside>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import request from '../utils/request';

const activeCategoryId = ref(''); // 一级分类id
const activeSubCategoryId = ref(''); // 二级分类id
const categories = ref([]); // 原始分类数据
const firstLevelCategories = ref([]); // 一级分类及其children

const emit = defineEmits(['category-selected']);

const buildCategoryTree = (flatList) => {
  const map = {};
  const roots = [];
  flatList.forEach(cat => {
    cat.children = [];
    map[cat.categoryId] = cat;
  });
  flatList.forEach(cat => {
    if (cat.parentId && map[cat.parentId]) {
      map[cat.parentId].children.push(cat);
    } else if (cat.categoryLevel === 1) {
      roots.push(cat);
    }
  });
  return roots;
};

const fetchCategories = async () => {
  const res = await request.get('/categories');
  categories.value = res.data;
  firstLevelCategories.value = buildCategoryTree(categories.value);
};

const selectAllProducts = () => {
  activeCategoryId.value = '';
  activeSubCategoryId.value = '';
  emit('category-selected', '');
};

const selectCategory = (category) => {
  if (activeCategoryId.value === category.categoryId) {
    // 再次点击收起
    activeCategoryId.value = '';
    activeSubCategoryId.value = '';
    emit('category-selected', '');
  } else {
    activeCategoryId.value = category.categoryId;
    activeSubCategoryId.value = '';
    emit('category-selected', category.categoryId);
  }
};

const selectSubCategory = (sub, parent) => {
  activeCategoryId.value = parent.categoryId;
  activeSubCategoryId.value = sub.categoryId;
  emit('category-selected', sub.categoryId);
};

const activeCategory = computed(() => {
  return firstLevelCategories.value.find(cat => cat.categoryId === activeCategoryId.value) || null;
});

const clearActiveCategory = () => {
  activeCategoryId.value = '';
  activeSubCategoryId.value = '';
};

onMounted(() => {
  fetchCategories();
});
</script>

<style scoped>
.sidebar {
  width: var(--sidebar-width);
  padding: 0;
  border: none;
  height: fit-content;
  position: relative;
  top: calc(var(--header-height) + var(--spacing-4));
}

.sidebar-header {
  padding: var(--spacing-6);
  border-bottom: 1px solid var(--gray-200);
}

.sidebar-title {
  font-size: var(--font-size-lg);
  font-weight: var(--font-weight-bold);
  color: var(--gray-900);
  margin: 0 0 var(--spacing-2) 0;
}

.sidebar-subtitle {
  font-size: var(--font-size-sm);
  color: var(--gray-600);
  margin: 0;
}

.category-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.category-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-3);
  padding: var(--spacing-4) var(--spacing-6);
  cursor: pointer;
  transition: all var(--transition-fast);
  border-bottom: 1px solid var(--gray-100);
  color: var(--gray-700);
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-medium);
  position: relative;
}

.category-item:last-child {
  border-bottom: none;
}

.category-item:hover {
  background-color: var(--gray-50);
  color: var(--gray-900);
  padding-left: calc(var(--spacing-6) + var(--spacing-2));
}

.category-item.active {
  background-color: var(--primary-light);
  color: var(--primary-color);
  border-left: 3px solid var(--primary-color);
  font-weight: var(--font-weight-semibold);
}

.category-item.active:hover {
  background-color: var(--primary-light);
  color: var(--primary-hover);
}

.category-icon {
  width: 18px;
  height: 18px;
  stroke: currentColor;
  fill: none;
  flex-shrink: 0;
  transition: all var(--transition-fast);
}

.category-item:hover .category-icon {
  transform: scale(1.1);
}

.all-products {
  font-weight: var(--font-weight-semibold);
  background-color: var(--gray-50);
  border-bottom: 2px solid var(--gray-200);
}

.all-products.active {
  background-color: var(--primary-light);
  color: var(--primary-color);
  border-left: 3px solid var(--primary-color);
}

.subcategory-list {
  list-style: none;
  padding: 0 0 0 30px;
  margin: 0;
  background: #f9f9f9;
  border-left: 2px solid var(--primary-light);
}

.subcategory-item {
  padding: 8px 0;
  cursor: pointer;
  color: var(--gray-600);
  font-size: 14px;
  transition: color 0.2s;
}
.subcategory-item.active,
.subcategory-item:hover {
  color: var(--primary-color);
  font-weight: bold;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    width: 100%;
    position: static;
    margin-bottom: var(--spacing-4);
  }
  .sidebar-header {
    padding: var(--spacing-4);
  }
  .category-item {
    padding: var(--spacing-3) var(--spacing-4);
  }
  .category-item:hover {
    padding-left: calc(var(--spacing-4) + var(--spacing-2));
  }
  .subcategory-list {
    padding-left: 15px;
  }
}

/* 手风琴动画 */
.accordion-enter-active, .accordion-leave-active {
  transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s;
  overflow: hidden;
}
.accordion-enter-from, .accordion-leave-to {
  max-height: 0;
  opacity: 0;
}
.accordion-enter-to, .accordion-leave-from {
  max-height: 500px;
  opacity: 1;
}

.float-subcategory-box {
  position: absolute;
  top: 60px;
  left: 100%;
  min-width: 180px;
  background: rgba(255,255,255,0.95);
  box-shadow: 0 4px 16px rgba(0,0,0,0.08);
  border-radius: 8px;
  z-index: 10;
  padding: 16px 12px;
  margin-left: 12px;
  border: 1px solid var(--primary-light);
  transition: box-shadow 0.2s;
}
.float-subcategory-box:hover {
  box-shadow: 0 8px 24px rgba(0,0,0,0.12);
}
/* 动画 */
.float-subcategory-enter-active, .float-subcategory-leave-active {
  transition: opacity 0.25s, transform 0.25s;
}
.float-subcategory-enter-from, .float-subcategory-leave-to {
  opacity: 0;
  transform: translateY(20px) scale(0.98);
}
.float-subcategory-enter-to, .float-subcategory-leave-from {
  opacity: 1;
  transform: translateY(0) scale(1);
}
</style>